package listeners;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import server.Conf;

public class BackupServerListener extends Thread{
	
	private static final int PORT_BEATER = 5220;
	//private static final int PORT_INSTR = 5230;
	
	protected boolean active;
	
	protected ServerSocket serverSocket;
	
	private Conf conf;
	
	public BackupServerListener(Conf conf) throws IOException{
		
		active = true;
		
		serverSocket = new ServerSocket(PORT_BEATER);
		serverSocket.setSoTimeout(1200);
		
		this.conf = conf;
	}
	
	public void run(){
		
		while(active){
		
			try {
				Boolean serverAlive = false;
				
				Socket beatSocket = serverSocket.accept();
				ObjectInputStream ois = new ObjectInputStream(beatSocket.getInputStream());
				serverAlive = (Boolean)ois.readObject();
				
				conf.setBackupServerActive(serverAlive);
				
				beatSocket.close();
			}
			catch(SocketTimeoutException e){
				conf.setBackupServerActive(false);
			}
			catch (IOException e) {
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

}
